//
//  SearchViewController.m
//  CarOfHome2
//
//  Created by dlios on 15/9/23.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchCell.h"
#import "NetworkHandle.h"
#import "SearchModel.h"
#import "SearchView.h"
#import "ListViewController.h"

@interface SearchViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSDictionary *brandDic;
@property (nonatomic, strong) NSMutableArray *lettersArr;
@property (nonatomic, strong) NSMutableArray *indexLetterArr;
@property (nonatomic, strong) SearchView *searchView;
@property (nonatomic, strong) MBProgressHUD *HUD;

@end

@implementation SearchViewController

- (void)viewWillAppear:(BOOL)animated
{

    
    self.searchView = [[SearchView alloc] initWithFrame:CGRectMake(SAWindth * 375, 0,  SAWindth * 275, SAHeight * 667)];

    AppDelegate *dele = [[UIApplication sharedApplication]delegate];
    if (dele.isNight == 1) {
        self.tableView.backgroundColor = [UIColor blackColor];
        [self.tableView reloadData];
    }
    else{
        self.tableView.backgroundColor = [UIColor whiteColor];
        [self.tableView reloadData];
    }
    self.searchView = [[SearchView alloc] initWithFrame:CGRectMake(375, 0, 275, 667)];
    
    [self.view addSubview:self.searchView];
    
    if (self.lettersArr == 0)
    {
        [self dataHandle];
        [self Open];
        [self.tableView.header beginRefreshing];
    }
}

#pragma mark -
- (void)Open
{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.labelText = @"加载中..";
    [self.HUD show:YES];
    self.view.userInteractionEnabled = NO;
    
}
- (void)Close
{
    [self.HUD hide:YES afterDelay:2];
    self.view.userInteractionEnabled = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = @"品牌大全";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"list"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"BBJJ"]];
    
//    [self dataHandle];
    [self tableViewSubview];
    
}


- (void)dataHandle
{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        NSMutableString *url = [NSMutableString stringWithFormat:@"%s",brand];
        [NetworkHandle GETWithURL:url complication:^(id result) {
            self.brandDic = result;
            
            /*将字典存入缓存*/
            NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
            
            NSString *dicPath = [cachePath stringByAppendingPathComponent:@"searchCar.plist"];
            [self.brandDic writeToFile:dicPath atomically:YES];
            
            self.lettersArr = [NSMutableArray array];
            self.indexLetterArr = [NSMutableArray array];
            
            self.lettersArr = [[self.brandDic objectForKey:@"letters"] mutableCopy];
            [self.lettersArr removeObjectAtIndex:0];
            for (int i = 0; i<self.lettersArr.count; i++)
            {
                
                NSString *str = [self.lettersArr[i] objectForKey:@"letter"];
                int temp = [str characterAtIndex:0];
                if (temp>=97 && temp<=122) {
                    
                    int temp = [str characterAtIndex:0]-32;
                    NSString *tempStr = [NSString stringWithFormat:@"%c" , temp];
                    [self.indexLetterArr addObject:tempStr];
                }
                else{
                    [self.indexLetterArr addObject:str];
                }
                
            }
            
            self.tableView.userInteractionEnabled = YES;
            [self.tableView reloadData];
            [self Close];
            [self.tableView.header endRefreshing];
            
        }];
    }];

}


- (void)tableViewSubview
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) style:UITableViewStylePlain];
    self.tableView.sectionIndexColor = [UIColor colorWithRed:36.0f/255 green:169.0f/255 blue:225.0f/255 alpha:1];
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = 0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[SearchCell class] forCellReuseIdentifier:@"reuse"];
    
}


#pragma mark - 设置tableView分区数
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.lettersArr.count;
}


#pragma mark - 设置tableView行数
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = [self.lettersArr[section] objectForKey:@"brands"];
    return arr.count;
}

#pragma mark - 设置行高
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return SAHeight * 50;
}



#pragma mark - 设置header标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    
    return self.indexLetterArr[section];
}

#pragma mark - 设置footer高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

#pragma mark - 设置header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return SAHeight * 30;
}

#pragma mark - 设置索引
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return self.indexLetterArr;
}


#pragma mark - 设置tableViewCell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse"];
    
    SearchModel *model = [[SearchModel alloc]init];
    NSArray *arr = [self.lettersArr[indexPath.section] objectForKey:@"brands"];
    NSDictionary *dic = arr[indexPath.row];
    [model setValuesForKeysWithDictionary:dic];
    cell.model = model;
    
    return cell;
}


#pragma mark - 选中方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = [self.lettersArr[indexPath.section] objectForKey:@"brands"];
    NSDictionary *dic = arr[indexPath.row];
    NSMutableArray *subBrands = [[dic objectForKey:@"subBrands"] mutableCopy];
    NSString *str = [dic objectForKey:@"name"];
    
    ListViewController *list = [[ListViewController alloc] init];
    
    list.arr = subBrands;
    list.title = str;
    
    [self.navigationController pushViewController:list animated:YES];
    

}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
